import { h, defineComponent, ref, onUnmounted, watch } from 'vue'
import { ElTooltip, ElInput, ElButton, ElAlert, ElDivider, ElTag } from 'element-plus'
import { RefreshRight, List, View } from '@element-plus/icons-vue'
import { jobApi } from '@/api/job'

// 预设的 Cron 表达式选项
const cronPresets = [
  { label: '每分钟', value: '0 * * * * ?', desc: '每分钟执行一次' },
  { label: '每5分钟', value: '0 */5 * * * ?', desc: '每5分钟执行一次' },
  { label: '每10分钟', value: '0 */10 * * * ?', desc: '每10分钟执行一次' },
  { label: '每30分钟', value: '0 */30 * * * ?', desc: '每30分钟执行一次' },
  { label: '每小时', value: '0 0 * * * ?', desc: '每小时执行一次' },
  { label: '每天凌晨', value: '0 0 0 * * ?', desc: '每天凌晨0点执行' },
  { label: '每天上午9点', value: '0 0 9 * * ?', desc: '每天上午9点执行' },
  { label: '每周一', value: '0 0 9 ? * MON', desc: '每周一上午9点执行' },
  { label: '每月1号', value: '0 0 9 1 * ?', desc: '每月1号上午9点执行' },
]

// 将 CronPreview 组件定义移到外部，避免重复创建
const CronPreview = defineComponent({
  name: 'CronPreview',
  props: { modelValue: { type: String, default: '' } },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const times = ref([])
    const loading = ref(false)
    const error = ref('')
    const showPresets = ref(false)
    const containerRef = ref(null)

    const preview = async () => {
      error.value = ''
      times.value = []
      if (!props.modelValue) {
        error.value = '请输入有效的 Cron 表达式'
        return
      }
      try {
        loading.value = true
        const res = await jobApi.nextTimes(props.modelValue)
        times.value = Array.isArray(res) ? res : []
      } catch (e) {
        error.value = '解析失败，请检查表达式'
      } finally {
        loading.value = false
      }
    }

    const selectPreset = (preset) => {
      emit('update:modelValue', preset.value)
      showPresets.value = false
    }

    // 点击外部关闭预设面板
    const handleClickOutside = (event) => {
      if (showPresets.value && containerRef.value && !containerRef.value.contains(event.target)) {
        showPresets.value = false
      }
    }

    // 监听点击事件 - 使用 nextTick 确保组件已挂载
    if (typeof window !== 'undefined') {
      const addListener = () => {
        document.addEventListener('click', handleClickOutside, true)
      }

      // 延迟添加监听器，确保组件已渲染
      setTimeout(addListener, 100)
    }

    // 组件卸载时移除事件监听
    onUnmounted(() => {
      if (typeof window !== 'undefined') {
        document.removeEventListener('click', handleClickOutside, true)
      }
    })

    return () =>
      h(
        'div',
        {
          ref: containerRef,
          class: 'cron-preview',
          style: 'position: relative;',
        },
        [
          // 输入框和按钮容器
          h(
            'div',
            { style: 'display: flex; gap: 12px; align-items: flex-start; margin-bottom: 12px;' },
            [
              // 输入框
              h('div', { style: 'flex: 1; min-width: 0;' }, [
                h(ElInput, {
                  modelValue: props.modelValue,
                  'onUpdate:modelValue': (v) => emit('update:modelValue', v),
                  placeholder: '例如 0 */5 * * * ?',
                  clearable: true,
                  style: 'width: 100%;',
                  props: {
                    clearable: true,
                    'show-word-limit': false,
                  },
                }),
              ]),
              // 按钮组
              h(
                'div',
                {
                  style: 'display: flex; gap: 8px; flex-shrink: 0;',
                  class: 'cron-buttons-desktop',
                },
                [
                  h(
                    ElButton,
                    {
                      type: 'default',
                      icon: List,
                      onClick: () => (showPresets.value = !showPresets.value),
                      style: 'white-space: nowrap;',
                    },
                    () => '预设',
                  ),
                  h(
                    ElButton,
                    {
                      type: 'primary',
                      icon: RefreshRight,
                      loading: loading.value,
                      onClick: preview,
                      style: 'white-space: nowrap;',
                    },
                    () => '解析',
                  ),
                ],
              ),
            ],
          ),

          // 移动端按钮行（CSS控制显示）
          h(
            'div',
            {
              style: 'display: flex; gap: 8px; align-items: center; margin-bottom: 12px;',
              class: 'cron-buttons-mobile',
            },
            [
              h(
                ElButton,
                {
                  type: 'default',
                  icon: List,
                  onClick: () => (showPresets.value = !showPresets.value),
                  style: 'flex: 1;',
                },
                () => '预设',
              ),
              h(
                ElButton,
                {
                  type: 'primary',
                  icon: RefreshRight,
                  loading: loading.value,
                  onClick: preview,
                  style: 'flex: 1;',
                },
                () => '解析',
              ),
            ],
          ),

          // 预设选项面板
          showPresets.value
            ? h(
                'div',
                {
                  style: 'position: relative; margin-bottom: 12px;',
                  class: 'cron-presets',
                },
                [
                  h(
                    'div',
                    {
                      style:
                        'padding: 16px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);',
                    },
                    [
                      h(
                        'div',
                        {
                          style:
                            'font-size: 14px; color: #6c757d; margin-bottom: 12px; font-weight: 500;',
                        },
                        '常用表达式',
                      ),
                      h(
                        'div',
                        {
                          style:
                            'display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; max-height: 200px; overflow-y: auto;',
                        },
                        cronPresets.map((preset) =>
                          h(
                            'div',
                            {
                              key: preset.value,
                              class: 'preset-item',
                              style:
                                'padding: 12px; background: white; border: 1px solid #dee2e6; border-radius: 6px; cursor: pointer; transition: all 0.2s ease;',
                              onClick: () => selectPreset(preset),
                            },
                            [
                              h(
                                'div',
                                {
                                  style:
                                    'font-size: 14px; font-weight: 500; color: #495057; margin-bottom: 4px;',
                                },
                                preset.label,
                              ),
                              h(
                                'div',
                                {
                                  style:
                                    'font-size: 12px; color: #6c757d; font-family: monospace; margin-bottom: 2px;',
                                },
                                preset.value,
                              ),
                              h(
                                'div',
                                {
                                  style: 'font-size: 11px; color: #868e96;',
                                },
                                preset.desc,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              )
            : null,

          // 错误提示
          error.value
            ? h(ElAlert, {
                title: error.value,
                type: 'error',
                showIcon: true,
                closable: false,
                style: 'margin-bottom: 12px;',
              })
            : null,

          // 执行时间展示
          times.value.length
            ? h('div', { style: 'margin-top: 12px;' }, [
                h(ElDivider, { contentPosition: 'left' }, { default: () => '未来5次执行时间' }),
                h(
                  'div',
                  { style: 'display: flex; flex-direction: column; gap: 8px; margin-top: 12px;' },
                  times.value.map((t, idx) =>
                    h(
                      'div',
                      {
                        key: `${t}-${idx}`,
                        style:
                          'display:flex; align-items:center; gap:12px; padding: 8px 12px; background: #f8f9fa; border-radius: 6px;',
                      },
                      [
                        h(ElTag, { type: 'info' }, () => String(idx + 1)),
                        h('span', { style: 'font-size: 13px; font-family: monospace;' }, t),
                      ],
                    ),
                  ),
                ),
              ])
            : null,
        ],
      )
  },
})

// 表单配置
export const formConfig = [
  {
    field: 'name',
    label: '任务名',
    component: 'Input',
    placeholder: '请输入任务名',
    editDisabled: true,
    rules: [{ required: true, message: '请输入任务名', trigger: 'blur' }],
  },
  {
    field: 'group',
    label: '分组',
    component: 'Input',
    placeholder: '请输入分组',
    editDisabled: true,
    rules: [{ required: true, message: '请输入分组', trigger: 'blur' }],
  },
  {
    field: 'classPath',
    label: 'Job类路径',
    component: 'Input',
    placeholder: '例如 top.bug.blog.schedule.job.DemoJob',
    editDisabled: true,
    rules: [{ required: true, message: '请输入类路径', trigger: 'blur' }],
  },
  {
    field: 'cron',
    label: 'Cron表达式',
    component: 'Input',
    placeholder: '例如 0 */5 * * * ?',
    render: (formData) => {
      return h(CronPreview, {
        modelValue: formData.cron,
        'onUpdate:modelValue': (v) => (formData.cron = v),
      })
    },
    rules: [{ required: true, message: '请输入Cron表达式', trigger: 'blur' }],
  },
  {
    field: 'description',
    label: '描述',
    component: 'Input',
    props: { type: 'textarea', rows: 3 },
    placeholder: '可选',
  },
  {
    field: 'jobData',
    label: '任务参数',
    component: 'Input',
    placeholder: 'JSON格式参数，例如：{"key1":"value1","key2":"value2"}',
    render: (formData, { isEdit }) => {
      const JobDataEditor = defineComponent({
        name: 'JobDataEditor',
        props: { modelValue: { type: Object, default: () => ({}) } },
        emits: ['update:modelValue'],
        setup(props, { emit }) {
          const showEditor = ref(false)
          const jsonString = ref('')
          const error = ref('')
          const isValidJson = ref(true)

          // 初始化JSON字符串
          const initJsonString = () => {
            try {
              jsonString.value = JSON.stringify(props.modelValue, null, 2)
              error.value = ''
              isValidJson.value = true
            } catch (e) {
              jsonString.value = '{}'
              error.value = ''
              isValidJson.value = true
            }
          }

          // 监听props变化
          watch(() => props.modelValue, initJsonString, { immediate: true })

          // 验证JSON格式
          const validateJson = (jsonStr) => {
            try {
              JSON.parse(jsonStr)
              error.value = ''
              isValidJson.value = true
              return true
            } catch (e) {
              error.value = 'JSON格式错误: ' + e.message
              isValidJson.value = false
              return false
            }
          }

          // 应用JSON
          const applyJson = () => {
            if (validateJson(jsonString.value)) {
              try {
                const parsed = JSON.parse(jsonString.value)
                emit('update:modelValue', parsed)
                showEditor.value = false
              } catch (e) {
                error.value = '解析失败: ' + e.message
              }
            }
          }

          // 重置为空对象
          const resetToEmpty = () => {
            jsonString.value = '{}'
            emit('update:modelValue', {})
            showEditor.value = false
          }

          // 格式化JSON
          const formatJson = () => {
            if (validateJson(jsonString.value)) {
              try {
                const parsed = JSON.parse(jsonString.value)
                jsonString.value = JSON.stringify(parsed, null, 2)
              } catch (e) {
                // 忽略格式化错误
              }
            }
          }

          return () =>
            h('div', { class: 'job-data-editor' }, [
              // 按钮区域
              h(
                'div',
                {
                  style: 'display: flex; align-items: center; gap: 12px;',
                },
                [
                  h(
                    ElButton,
                    {
                      type: 'primary',
                      size: 'default',
                      icon: h('span', { style: 'font-size: 14px;' }, '⚙️'),
                      onClick: () => (showEditor.value = true),
                      style: 'min-width: 120px;',
                    },
                    () => '配置任务参数',
                  ),
                  // 查看参数按钮
                  Object.keys(props.modelValue).length > 0
                    ? h(
                        ElTooltip,
                        {
                          content: JSON.stringify(props.modelValue, null, 2),
                          placement: 'top',
                          effect: 'dark',
                          showAfter: 200,
                          popperClass: 'job-data-tooltip',
                        },
                        () =>
                          h(
                            ElButton,
                            {
                              type: 'text',
                              size: 'small',
                              icon: View,
                              style: 'padding: 4px; min-width: auto; color: #0369a1;',
                            },
                            () => '',
                          ),
                      )
                    : null,
                ],
              ),

              // 编辑器弹窗
              showEditor.value
                ? h(
                    'div',
                    {
                      style:
                        'position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 2000;',
                    },
                    [
                      // 遮罩层
                      h('div', {
                        style:
                          'position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); backdrop-filter: blur(4px);',
                        onClick: () => (showEditor.value = false),
                      }),
                      // 弹窗内容
                      h(
                        'div',
                        {
                          style:
                            'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 600px; max-width: 90vw; max-height: 80vh; padding: 24px; background: white; border-radius: 12px; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); display: flex; flex-direction: column;',
                          class: 'job-data-editor-modal',
                          onClick: (e) => e.stopPropagation(),
                        },
                        [
                          // 标题栏
                          h(
                            'div',
                            {
                              style:
                                'display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid #f0f0f0;',
                            },
                            [
                              h(
                                'h3',
                                {
                                  style:
                                    'margin: 0; font-size: 18px; font-weight: 600; color: #333;',
                                },
                                '任务参数编辑器',
                              ),
                              h(
                                ElButton,
                                {
                                  type: 'text',
                                  size: 'small',
                                  onClick: () => (showEditor.value = false),
                                  style: 'padding: 4px; min-width: auto; color: #999;',
                                },
                                () => '✕',
                              ),
                            ],
                          ),

                          // 文本区域
                          h('div', { style: 'flex: 1; margin-bottom: 16px;' }, [
                            h('textarea', {
                              value: jsonString.value,
                              onInput: (e) => {
                                jsonString.value = e.target.value
                                validateJson(jsonString.value)
                              },
                              style:
                                'width: 100%; height: 280px; padding: 16px; border: 1px solid #e0e0e0; border-radius: 8px; font-family: "Consolas", "Monaco", "Courier New", monospace; font-size: 14px; line-height: 1.6; resize: vertical; outline: none; background: #fafafa;',
                              placeholder:
                                '请输入JSON格式的参数，例如：\n{\n  "timeout": 30000,\n  "retryCount": 3,\n  "email": "admin@example.com",\n  "config": {\n    "debug": true,\n    "logLevel": "info"\n  }\n}',
                            }),
                          ]),

                          // 错误提示
                          error.value
                            ? h(
                                'div',
                                {
                                  style:
                                    'margin-bottom: 16px; padding: 12px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; color: #dc2626; font-size: 13px; line-height: 1.4;',
                                },
                                error.value,
                              )
                            : null,

                          // 按钮区域
                          h(
                            'div',
                            {
                              style:
                                'display: flex; flex-direction: column; gap: 12px; padding-top: 16px; border-top: 1px solid #f0f0f0;',
                              class: 'mobile-button-container',
                            },
                            [
                              // 移动端按钮布局：上下两行
                              h(
                                'div',
                                {
                                  style: 'display: flex; gap: 8px; justify-content: space-between;',
                                },
                                [
                                  h(
                                    ElButton,
                                    {
                                      type: 'default',
                                      size: 'default',
                                      onClick: formatJson,
                                      disabled: !isValidJson.value,
                                      style: 'flex: 1; min-width: 0; padding: 8px 12px;',
                                    },
                                    () => '格式化',
                                  ),
                                  h(
                                    ElButton,
                                    {
                                      type: 'default',
                                      size: 'default',
                                      onClick: resetToEmpty,
                                      style: 'flex: 1; min-width: 0; padding: 8px 12px;',
                                    },
                                    () => '清空',
                                  ),
                                ],
                              ),
                              h('div', { style: 'display: flex; gap: 8px;' }, [
                                h(
                                  ElButton,
                                  {
                                    type: 'default',
                                    size: 'default',
                                    onClick: () => (showEditor.value = false),
                                    style: 'flex: 1; min-width: 0; padding: 10px 12px;',
                                  },
                                  () => '取消',
                                ),
                                h(
                                  ElButton,
                                  {
                                    type: 'primary',
                                    size: 'default',
                                    onClick: applyJson,
                                    disabled: !isValidJson.value,
                                    style: 'flex: 1; min-width: 0; padding: 10px 12px;',
                                  },
                                  () => '确定',
                                ),
                              ]),
                            ],
                          ),
                        ],
                      ),
                    ],
                  )
                : null,
            ])
        },
      })

      return h(JobDataEditor, {
        modelValue: formData.jobData || {},
        'onUpdate:modelValue': (v) => (formData.jobData = v),
      })
    },
  },
]

export const getDefaultFormData = () => ({
  id: '',
  name: '',
  group: 'DEFAULT',
  classPath: 'top.bug.blog.schedule.job.',
  cron: '',
  description: '',
  jobData: {},
})

// 添加样式
const style = document.createElement('style')
style.textContent = `
  .cron-presets {
    animation: fadeIn 0.2s ease-in-out;
    backdrop-filter: blur(8px);
  }

  .cron-presets .preset-item {
    transition: all 0.2s ease;
    flex-shrink: 0;
  }

  .cron-presets .preset-item:hover {
    border-color: #409eff !important;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15) !important;
    transform: translateY(-1px);
  }

  .cron-presets::-webkit-scrollbar {
    width: 4px;
  }

  .cron-presets::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
  }

  .cron-presets::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
  }

  .cron-presets::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  /* 桌面端默认样式：输入框和按钮同行 */
  .cron-preview {
    .cron-buttons-desktop {
      display: flex !important;
    }

    .cron-buttons-mobile {
      display: none !important;
    }
  }

  /* 防止输入框宽度变化 */
  .cron-preview .el-input {
    width: 100% !important;
  }

  .cron-preview .el-input__wrapper {
    width: 100% !important;
    min-width: 0 !important;
  }

  .cron-preview .el-input__inner {
    width: 100% !important;
    min-width: 0 !important;
  }

  .cron-preview .el-input__suffix {
    position: absolute !important;
    right: 8px !important;
  }

  .cron-preview .el-input__suffix-inner {
    display: flex !important;
    align-items: center !important;
  }

  /* 任务参数编辑器样式 */
  .job-data-editor {
    position: relative;
  }

  .job-data-editor-modal {
    animation: modalFadeIn 0.3s ease-out;
  }

  .job-data-editor textarea:focus {
    border-color: #409eff !important;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1) !important;
    background: white !important;
  }

  .job-data-editor textarea:hover {
    border-color: #c0c4cc !important;
  }

  .job-data-editor .el-button {
    border-radius: 6px;
    font-weight: 500;
  }

  .job-data-editor .el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
    border: none;
  }

  .job-data-editor .el-button--primary:hover {
    background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
  }

  /* 参数预览提示样式 */
  .job-data-editor .el-tooltip__trigger {
    transition: all 0.2s ease;
  }

  .job-data-editor .el-tooltip__trigger:hover {
    background: #e0f2fe !important;
    border-color: #7dd3fc !important;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(3, 105, 161, 0.15);
  }

  @keyframes modalFadeIn {
    from {
      opacity: 0;
      transform: translate(-50%, -50%) scale(0.9);
    }
    to {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1);
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(-8px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }

  /* 工具提示样式 */
  .job-data-tooltip {
    max-width: 400px !important;
    font-family: "Consolas", "Monaco", "Courier New", monospace !important;
    font-size: 12px !important;
    line-height: 1.4 !important;
    white-space: pre-wrap !important;
    word-break: break-all !important;
  }

  .job-data-tooltip .el-tooltip__popper {
    background: #2d3748 !important;
    color: #e2e8f0 !important;
    border: 1px solid #4a5568 !important;
    border-radius: 8px !important;
    padding: 12px !important;
  }

  /* 移动端优化样式 */
  @media screen and (max-width: 768px) {
    .cron-preview {
      .cron-buttons-desktop {
        display: none !important;
      }

      .cron-buttons-mobile {
        display: flex !important;
      }

      .cron-buttons-mobile .el-button {
        height: 44px !important;
        font-size: 15px !important;
        padding: 12px !important;
        border-radius: 8px !important;
        flex: 1 !important;
      }
    }

    .cron-presets {
      position: fixed !important;
      top: 50% !important;
      left: 50% !important;
      transform: translate(-50%, -50%) !important;
      width: calc(100vw - 32px) !important;
      max-width: 400px !important;
      z-index: 10001 !important;
      margin: 0 !important;

      > div:last-child {
        max-height: 50vh !important;
        overflow-y: auto !important;
        padding-right: 0 !important;
      }
    }

    .job-data-editor-modal {
      width: calc(100vw - 24px) !important;
      max-width: calc(100vw - 24px) !important;
      height: calc(100vh - 60px) !important;
      max-height: calc(100vh - 60px) !important;
      padding: 16px !important;
      border-radius: 12px !important;
      overflow: hidden !important;
      display: flex !important;
      flex-direction: column !important;

      > div:first-child {
        flex-shrink: 0 !important;
        margin-bottom: 16px !important;
      }

      div:nth-child(2) {
        flex: 1 !important;
        margin-bottom: 16px !important;
        min-height: 0 !important;

        textarea {
          height: 100% !important;
          width: 100% !important;
          font-size: 16px !important;
          resize: none !important;
          border: 1px solid #e0e0e0 !important;
          box-sizing: border-box !important;
        }
      }

      .mobile-button-container {
        flex-shrink: 0 !important;
        background: white !important;
        padding-top: 12px !important;
        padding-bottom: 0 !important;
      }

      .mobile-button-container .el-button {
        height: 40px !important;
        font-size: 14px !important;
        border-radius: 6px !important;
        padding: 8px 12px !important;
        flex: 1 !important;
        min-width: 0 !important;
      }
    }
  }

  @media screen and (max-width: 375px) {
    .cron-presets {
      width: calc(100vw - 16px) !important;

      > div:last-child {
        max-height: 40vh !important;
      }
    }

    .job-data-editor-modal {
      padding: 12px !important;
      height: calc(100vh - 40px) !important;
      max-height: calc(100vh - 40px) !important;

      > div:first-child {
        margin-bottom: 12px !important;
      }

      div:nth-child(2) {
        margin-bottom: 12px !important;

        textarea {
          font-size: 16px !important;
          padding: 12px !important;
          box-sizing: border-box !important;
        }
      }

      .mobile-button-container {
        padding-top: 8px !important;
        padding-bottom: 0 !important;

        .el-button {
          height: 36px !important;
          font-size: 13px !important;
          padding: 6px 8px !important;
        }
      }
    }
  }

  /* 减少动画的用户偏好 */
  @media (prefers-reduced-motion: reduce) {
    .cron-presets {
      animation: none !important;
    }

    .cron-presets .preset-item {
      transition: none !important;
    }

    .job-data-editor-modal {
      animation: none !important;
    }
  }
`
document.head.appendChild(style)
